<?php
declare (strict_types = 1);

namespace app\command;

use app\command\model\Perform;
use app\common\model\User;
use app\store\model\store\Dermember;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\store\model\User as UserModel;

class Wine extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('perform')
            ->setDescription('the perform command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('dermember表团队销售统计-定时任务开始执行');
        $derModel = new Dermember();
        $jxsArr = $derModel->where(['is_delete'=>0])->with('user')->select();
        foreach ($jxsArr as $value){
            $id = $value['id'];
            $user_id = $value['user_id'];
            $getPerform = $this->getPerform($user_id,$derModel); // 团队收益
            $expend_money = $value['pay_money']; // 个人收益
            $total = $getPerform['total_expend_money'] + $expend_money;// 个人收益+团队收益 = 总收益
            $award = $this->getAward($total,$user_id)/100;// 收益百分比
            $award_money = floor($total*$award*100)/100;
            $derModel->where(['id'=>$id])->save([
                'total_expend_money'=>$total,
                'pcount' => $getPerform['pcount'],
                'award_money' => $award_money
            ]);
        }
        $output->writeln('dermember表团队销售统计-定时任务执行结束');
    }
    //查找子经销商业绩
    private function getPerform($pid,$derModel){
        $r = $derModel->where(['pid'=>$pid])->with('user')->select();
        $total_expend_money = 0;// 团队业绩
        foreach ($r as $value){
            $expend_money = $value['pay_money'];
            $total_expend_money += $expend_money;
        }
        //经销商个数
        $pcount = count($r);
        return [
            'total_expend_money' => $total_expend_money,
            'pcount' => $pcount
        ];
    }

    // 获取经销商奖励等级
    public function getAward($perform,$user_id){
        $leveData = Perform::getLevel($perform);
        if($leveData === false){
            return 0;
        }
        $gradeid = $leveData['gradeid'];
        $award = $leveData['award'];
        $gradeid2 = $leveData['gradeid2'];
        $award2 = $leveData['award2'];
        $grade_id = User::where(['user_id'=>$user_id])->value('grade_id');
        // 会员级别
        switch ($grade_id){
            case $gradeid:
                return $award;
            case $gradeid2:
                return $award2;
            default:
                return 0;
        }
    }
}
